import json
import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi import status
from fastapi.responses import JSONResponse, Response
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import FileResponse

from linux.work_flow import *
from fastapi import FastAPI, File, UploadFile
from pathlib import Path
import os
app = FastAPI()

class findItem(BaseModel):
    mode: str
    data: str
    # 抽取视频的条数
    video_total: int
    # 每条视频抽取的评论数
    comment_total: int


# 查看词云图
@app.get("/wordcloud/{name}.png")
async def read_image(name:str):
    return FileResponse('D:/PycharmProjects/tik-tok-comment-analysis/tik-tok_-comment_-analysis/files_fast/photo/{}.png'.format(name))


# 查视频
@app.post("/get_video/")
async def get_video(form: findItem):
    user_id = get_user_id(form.data)
    # 判断是否分析过这个id
    folder_path = "./linux/json/"  # 替换为您的文件夹路径
    target_string = "" + user_id + ".json"  # 替换为您要查找的字符串
    if check_file_exists(folder_path, target_string):
        with open(folder_path + target_string, 'r', encoding='utf-8') as file:
            data = json.load(file)
        return JSONResponse(
            status_code=status.HTTP_200_OK,
            content=data
        )
    else:
        video_total, comment_total, video_id_arr,user_tiktok_id,user_icon,Signatures,user_follow,user_fs, user_like, user_name, img_arr, img_text_arr, url_arr, like_arr = get_video_arr(user_id, form.video_total, form.comment_total)
        if not video_id_arr:
            return JSONResponse(
                status_code=status.HTTP_400_BAD_REQUEST,
                content={
                    'code': 400,
                    'message': "此人无视频，暂时无法分析"
                })
        return JSONResponse(
                status_code=status.HTTP_200_OK,
                content={
                        'code': 200,
                        'message': "Success",
                        'mode': form.mode,
                        'input_text': form.data,
                        'video': {
                            'img_arr': img_arr,
                            'img_text_arr': img_text_arr,
                            "url_arr": url_arr,
                            "like_arr": like_arr
                        },
                        'user_name': user_name,
                        'user_id': user_id

                    })

# 查视频加分析
@app.post("/get_video_analysis/")
async def get_video_analysis(form: findItem):
    user_id = get_user_id(form.data)
    # 判断是否分析过这个id
    folder_path = "./linux/json/"  # 替换为您的文件夹路径
    target_string = "" + user_id + ".json"  # 替换为您要查找的字符串
    if check_file_exists(folder_path, target_string):
        with open(folder_path + target_string, 'r', encoding='utf-8') as file:
            data = json.load(file)
        return JSONResponse(
            status_code=status.HTTP_200_OK,
            content=data
        )
    else:
        video_total, comment_total, video_id_arr,user_tiktok_id,user_icon, Signatures,user_follow,user_fs, user_like, user_name, img_arr, img_text_arr, url_arr, like_arr = get_video_arr(
            user_id, form.video_total, form.comment_total)
        if not video_id_arr:
            return JSONResponse(
                status_code=status.HTTP_400_BAD_REQUEST,
                content={
                    'code': 400,
                    'message': "此人无视频，暂时无法分析"
                })
        requerst_tiktok(video_id_arr, comment_total, user_name)
        data_preprocessing(user_name)
        get_label(user_name)
        drew_wordcloud(user_name)
        load_linux_spark()
        out_to_front()
        # 评论人数最多的省，最大的省份的人数百分比，年,按年的白子数，按年的黑子数,时间热力图，总体白子黑子饼图1，2,各省的数据展示
        hour_max_count, hour_max, max_weekday, max_weekday_pair, province, province_max, year_arr, result1, result2, result4_date_count, value1, value2, province_top7, province_top7_value1, province_top7_value2, province_top7_revenue, province_top7_expenditures = out_to_front()
        content = {
            'code': 200,
            'message': "Success",
            'mode': form.mode,
            'input_text': form.data,
            'video':{
                'img_arr': img_arr,
                'img_text_arr': img_text_arr,
                "url_arr": url_arr,
                "like_arr": like_arr
            },
            'user_icon':user_icon,
            'user_tiktok_id':user_tiktok_id,
            'Signatures':Signatures,
            'user_follow':user_follow,
            'user_name': user_name,
            'user_id': user_id,
            'total': value1 + value2,
            'user_like': user_like,
            'user_fs': user_fs,
            'hour_max': hour_max,
            'hour_max_count_pair': (int((hour_max_count / (value1 + value2)) * 10000)) / 100,
            'max_weekday': max_weekday,
            'max_weekday_pair': max_weekday_pair,
            'province': {
                "province": province[0],
                "province_max": province_max,
            },
            'pie': {
                "value1": value1,
                "value2": value2,
            },
            'pie_cal': {
                "date": year_arr,
                "value1": result1.tolist(),
                "value2": result2.tolist()
            },
            "cal": result4_date_count,
            "bar_line": {
                "province_top7": province_top7,
                "province_top7_value1": province_top7_value1,
                "province_top7_value2": province_top7_value2,
                "province_top7_revenue": province_top7_revenue,
                "province_top7_expenditures": province_top7_expenditures
            }
        }

        # 将列表转换为JSON字符串
        json_data = json.dumps(content, ensure_ascii=False, indent=4)
        # 将JSON字符串写入到文件中
        with open('./linux/json/' + user_id + '.json', 'w', encoding='utf-8') as f:
            f.write(json_data)

        # 删除out1,2的csv文件

        # 创建待办事项的逻辑
        return JSONResponse(
            status_code=status.HTTP_200_OK,
            content=content
        )

# 只分析不查视频


@app.post("/todos/")
async def create_todo():
    # 创建待办事项的逻辑
    return "todo_id"


if __name__ == '__main__':
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    uvicorn.run(app)

